<template>
  <section>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-button type="primary">添加角色</el-button>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, index1) in scope.row.children"
              :key="index"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row, item1.id)" closable>
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      @close="removeRightById(scope.row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      @close="removeRightById(scope.row, item3.id)"
                      closable
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作" prop="roleName">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              @click="showSetRightDialog(scope.row)"
              type="warning"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>
<script>
import { requestGet, requestDelete, requestPost } from "../../request/request";
export default {
  name: "",
  data() {
    return {
      rolesList: [],
      dialogVisible: false,
      rightslist: [],
      treeProps: {
        label: "authName",
        children: "children"
      },
      // 打开权限列表默认选中的值
      defKeys: [],
      // 分配当前角色的id
      roleId: ""
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 点击确定按钮为角色授权权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");
      const { data: res } = await requestPost(`roles/${this.roleId}/rights`, {
        rids: idStr
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.$message.success(res.meta.msg);
      }
      this.getRolesList();
      this.dialogVisible = false;
    },
    // 监听关闭分配权限对话框时将默认选项清空
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 通过递归的方式，获取角色下所有的三级权限id，并保存到defkeys数组中
    getLeafKeys(node, arr) {
      // 如果当前node节点不包括children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    // 点击分配权限显示分配权限对话框同时并获取所有权限的数据
    async showSetRightDialog(role) {
      this.roleId = role.id;
      // 获取所有权限数据
      const { data: res } = await requestGet("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限数据失败");
      }

      this.rightslist = res.data;

      this.getLeafKeys(role, this.defKeys);

      this.dialogVisible = true;
    },
    // 根据id删除用户三级权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该用户权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          console.log(role, rightId);
          const { data: res } = await requestDelete(
            `roles/${role.id}/rights/${rightId}`
          );
          console.log(res);
          if (res.meta.status !== 200) {
            this.$message.error("res.meta.msg");
            return;
          }
          this.$message.success(res.meta.msg);
          role.children = res.data;
        })
        .catch(() => {
          this.$message.info("已取消删除权限");
        });
    },
    // 获取权限列表数据
    async getRolesList() {
      const { data: res } = await requestGet("/roles");

      if (res.meta.status !== 200) {
        this.$message.error(this.meta.msg);
      } else {
        this.rolesList = res.data;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-card {
  margin-top: 30px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
